<template>
  <view class="page">
    <!-- 使用 z-paging 实现滚动和分页 -->
    <z-paging ref="paging" v-model="eventList" :fixed="true" safe-area-inset-bottom :default-page-size="20"
      :auto-show-back-to-top="true" :refresher-enabled="true" :loading-more-enabled="true" @query="queryList">
      <!-- 顶部固定区域 - 仅导航栏 -->
      <template #top>
        <view class="top-container">
          <view class="nav" :style="{ paddingTop: statusBarPx + 'px' }">
            <view class="nav-title">指标数据</view>
          </view>
          <!-- 功能卡片区域 -->
          <view class="feature-row">
            <view class="feature-card" @click="goToFinancialCalendar">
              <image class="feature-img" src="/static/images/data/large-position.png" mode="widthFix" />
            </view>
            <view class="feature-card" @click="goToWhalePosition">
              <image class="feature-img" src="/static/images/data/financial-calendar.png" mode="widthFix" />
            </view>
            <view class="feature-card" @click="goToWhaleAlert">
              <image class="feature-img" src="/static/images/data/chain-explorer.png" mode="widthFix" />
            </view>
          </view>
        </view>

        <!-- 新闻快讯 - 月份选择器 -->
        <view class="month-selector-wrapper">
          <!-- <view class="month-selector" @click="openMonthPicker">
            <text class="selected-year-month">{{ selectedYearMonth }}</text>
            <uv-icon name="calendar" size="20" color="#ffffff"></uv-icon>
          </view> -->
        </view>
      </template>

      <!-- 新闻快讯 (时间轴样式 - 按日期分组) -->
      <view class="news-section">
        <!-- 时间轴事件列表 - 按日期分组 -->
        <view class="news-timeline">
          <!-- 按日期分组的事件 -->
          <view 
            v-for="group in groupedEvents" 
            :key="group.date"
            class="news-date-group"
          >
            <!-- 日期标题 -->
            <view class="news-date-header">
              <view class="date-line"></view>
              <text class="date-text">{{ formatDateHeader(group) }}</text>
            </view>

            <!-- 该日期下的事件列表 -->
            <view class="news-list">
              <view 
                v-for="event in group.events" 
                :key="event.id"
                class="news-item"
                @click="goToNewsDetail(event)"
              >
                
                <!-- 事件内容 -->
                <view class="news-content">
                  <view class="news-top-time">
                    <view class="news-top-left-line"></view>
                      {{ event.timeOnly }}
                  </view>
                  <!-- 事件卡片 -->
                  <view class="news-card">
                    <!-- 标题 -->
                    <view class="news-title">{{ event.title }}</view>

                    <!-- 描述内容 - 使用 uv-parse 渲染 HTML，最多显示两行 -->
                    <view class="news-desc-wrapper">
                      <uv-parse :content="event.content" :selectable="false"></uv-parse>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 空状态 -->
          <view v-if="groupedEvents.length === 0 && !isLoading" class="empty-state">
            <text class="empty-text">暂无新闻快讯</text>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 月份选择器弹窗 -->
    <uv-picker
      ref="monthPicker"
      :columns="pickerColumns"
      :defaultIndex="pickerDefaultIndex"
      title="选择月份"
      keyName="label"
      :round="20"
      confirmColor="#00d4aa"
      @confirm="onMonthConfirm"
      @cancel="closeMonthPicker"
      @close="closeMonthPicker"
    ></uv-picker>
  </view>
</template>

<script>
import { getNewsPage } from '@/api/data'
import { getToken } from '@/utils/auth'

export default {
  data() {
    const sys = uni.getSystemInfoSync()
    const statusBarPx = sys.statusBarHeight || 0

    // 初始化日期
    const today = new Date()
    const year = today.getFullYear()
    const month = today.getMonth() + 1

    // 生成年份列表（2020-2030）
    const yearColumn = []
    for (let i = 2020; i <= 2030; i++) {
      yearColumn.push({
        label: `${i}年`,
        value: i
      })
    }

    // 生成月份列表（1-12月）
    const monthColumn = []
    for (let i = 1; i <= 12; i++) {
      monthColumn.push({
        label: `${i}月`,
        value: i
      })
    }

    return {
      statusBarPx,
      eventList: [], // 事件列表（z-paging）
      isLoading: false, // 加载状态
      fromDetailPage: false, // 标记是否从详情页返回
      isFirstLoad: true, // 标记是否首次加载

      // 月份选择器相关
      selectedYear: year,
      selectedMonth: month,
      pickerColumns: [yearColumn, monthColumn], // 选择器列数据
      pickerDefaultIndex: [year - 2020, month - 1], // 默认选中的索引
    }
  },

  computed: {
    /**
     * 显示的年月字符串
     */
    selectedYearMonth() {
      return `${this.selectedYear}年${this.selectedMonth}月`
    },

    /**
     * 按日期分组的事件列表
     */
    groupedEvents() {
      if (!this.eventList || this.eventList.length === 0) {
        return []
      }

      // 按日期分组
      const groups = {}
      const weekTexts = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

      this.eventList.forEach(event => {
        // 检查 time 字段是否存在
        if (!event.time) {
          console.warn('事件缺少 time 字段:', event)
          return
        }

        // 解析时间字符串 (格式: yyyy-MM-dd HH:mm:ss)
        const date = new Date(event.time.replace(/-/g, '/'))
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          console.warn('无效的时间格式:', event.time)
          return
        }

        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        const dateKey = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`

        if (!groups[dateKey]) {
          groups[dateKey] = {
            date: dateKey,
            year: year,
            month: month,
            day: day,
            weekday: weekTexts[date.getDay()],
            events: []
          }
        }

        // 添加只包含时间的字段
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')

        groups[dateKey].events.push({
          ...event,
          timeOnly: `${hours}:${minutes}`
        })
      })

      // 转换为数组并按日期排序
      const result = Object.values(groups).sort((a, b) => {
        return new Date(b.date) - new Date(a.date) // 降序排列，最新的在前
      })

      // 每个分组内的事件按时间排序
      result.forEach(group => {
        group.events.sort((a, b) => {
          const timeA = new Date(a.time.replace(/-/g, '/'))
          const timeB = new Date(b.time.replace(/-/g, '/'))
          return timeB - timeA // 降序排列
        })
      })

      return result
    }
  },
  onShow(){
    // 首次加载时，z-paging 会自动调用 queryList，不需要手动 reload
    if (this.isFirstLoad) {
      console.log('首次加载，z-paging 自动请求数据')
      this.isFirstLoad = false
      return
    }
    
    // 如果是从详情页返回的，不刷新列表
    if (this.fromDetailPage) {
      console.log('从详情页返回，跳过刷新')
      this.fromDetailPage = false // 重置标记
      return
    }
    
    // 确保 paging 组件已经初始化，刷新数据
    this.$nextTick(() => {
      if (this.$refs.paging) {
        this.$refs.paging.reload(true)
      }
    })
  },
  methods: {
    /**
     * z-paging 查询数据方法（服务端分页）
     * @param {Number} pageNo - 页码
     * @param {Number} pageSize - 每页数量
     */
    async queryList(pageNo, pageSize) {
      try {
        console.log('请求新闻快讯数据:', { pageNo, pageSize })

        this.isLoading = true

        // 调用新闻接口
        const response = await getNewsPage({
          pageNo: pageNo,
          pageSize: pageSize
        })

        console.log('新闻快讯响应:', response)

        // 获取分页数据
        const newsData = response.data || {}
        const records = newsData.records || []

        console.log('返回数据条数:', records.length)
        console.log('总记录数:', newsData.total)

        // 格式化数据
        const formattedData = records.map((item) => {
          return {
            id: item.id,
            title: item.title,
            content: item.content || '', // 直接使用原始 HTML 内容
            time: item.time,
            timestamp: item.timestamp
          }
        })

        this.isLoading = false

        // 完成加载
        this.$refs.paging.complete(formattedData)
      } catch (error) {
        console.error('加载新闻快讯失败:', error)

        this.isLoading = false

        // 加载失败
        this.$refs.paging.complete(false)

        uni.showToast({
          title: error.message || '加载失败，请重试',
          icon: 'none',
          duration: 2000,
        })
      }
    },

    /**
     * 格式化日期标题
     * @param {Object} group - 日期分组对象
     * @returns {String} 格式化后的日期字符串，如 "11/05 今天 星期三"
     */
    formatDateHeader(group) {
      const today = new Date()
      const groupDate = new Date(group.date)
      
      // 计算日期差
      const diffTime = today.setHours(0, 0, 0, 0) - groupDate.setHours(0, 0, 0, 0)
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
      
      let dayText = ''
      if (diffDays === 0) {
        dayText = '今天'
      } else if (diffDays === 1) {
        dayText = '昨天'
      } else if (diffDays === 2) {
        dayText = '前天'
      } else {
        dayText = ''
      }
      
      // 格式化为 "MM/DD"
      const monthStr = String(group.month).padStart(2, '0')
      const dayStr = String(group.day).padStart(2, '0')
      
      // 组合显示
      if (dayText) {
        return `${monthStr}/${dayStr} ${dayText} ${group.weekday}`
      } else {
        return `${monthStr}/${dayStr} ${group.weekday}`
      }
    },

    /**
     * 检查是否登录
     */
    checkLogin() {
      const token = getToken()
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/auth/login'
          })
        }, 1500)
        return false
      }
      return true
    },

    /**
     * 跳转到财经日历页面（无需登录）
     */
    goToFinancialCalendar() {
      uni.navigateTo({
        url: '/subPages/data/financial-calendar'
      })
    },
    
    /**
     * 跳转到大额转账页面（无需登录）
     */
    goToWhaleAlert() {
      uni.navigateTo({
        url: '/subPages/data/whale-alert'
      })
    },
    
    /**
     * 跳转到链上侦探页面（需要登录）
     */
    goToWhalePosition() {
      if (!this.checkLogin()) return
      uni.navigateTo({
        url: '/subPages/data/whale-position'
      })
    },
    
    /**
     * 跳转到新闻详情页面
     * @param {Object} newsItem - 新闻数据
     */
    goToNewsDetail(newsItem) {
      // 设置标记，表示即将跳转到详情页
      this.fromDetailPage = true

      // 将新闻数据存储到缓存
      try {
        uni.setStorageSync('current_news_detail', JSON.stringify(newsItem))
        console.log('新闻数据已存储到缓存:', newsItem.id)
      } catch (error) {
        console.error('存储新闻数据失败:', error)
      }

      // 跳转到详情页面
      uni.navigateTo({
        url: '/subPages/data/news-detail'
      })
    },

  },
}
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100vh;
  background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
}

.nav {
  position: relative;
  width: 100%;
  padding: 30rpx 0 24rpx;
}

.top-container {
  background: url('/static/images/data/top-bg.png') no-repeat;
  background-size: 100% 100%;
  width: 100%;
}

.nav-title {
  font-size: 34rpx;
  font-weight: 700;
  color: #2a2b2f;
  text-align: center;
}

.feature-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 18rpx;
  padding: 24rpx;
}

.feature-card {
  position: relative;
  width: 100%;
  border-radius: 20rpx;
}

.feature-img {
  width: 100%;
}

/* 月份选择器包装器 */
.month-selector-wrapper {
  // padding: 24rpx;  
  background: #ffffff;
}

/* 月份选择器 */
.month-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  background: linear-gradient(135deg, #00d4aa 0%, #00b894 100%);
  border-radius: 16rpx;
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
  }
}

.selected-year-month {
  font-size: 32rpx;
  font-weight: 700;
  color: #ffffff;
}

/* 快讯区域 */
.news-section {
  background: #f7f8fa;
  padding: 0 0 40rpx;
}

/* 快讯时间轴 */
.news-timeline {
  padding: 0;
}

/* 日期分组 */
.news-date-group {
  margin-bottom: 40rpx;
  padding-top: 20rpx;
  &:last-child {
    margin-bottom: 0;
  }
}

/* 日期标题 */
.news-date-header {
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  margin-bottom: 24rpx;
}

/* 日期左侧竖线 */
.date-line {
  width: 6rpx;
  height: 32rpx;
  background: #00d4aa;
  border-radius: 3rpx;
  margin-right: 16rpx;
}

/* 日期文字 */
.date-text {
  font-size: 28rpx;
  font-weight: 500;
  color: #303133;
  letter-spacing: 0.5rpx;
}

/* 快讯列表 */
.news-list {
  padding: 0 32rpx;
}

/* 快讯项 */
.news-item {
  position: relative;
  margin-bottom: 32rpx;
  cursor: pointer;
  transition: all 0.2s ease;

  &:last-child {
    margin-bottom: 0;
  }
  
  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
}

/* 左侧竖线 */

/* 快讯内容 */
.news-content {
  // padding-left: 24rpx;
  background: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx 0rpx;
}

/* 快讯卡片 */
.news-card {
  position: relative;
  padding: 0rpx 20rpx;
  padding-top: 26rpx;
}

/* 时间标签 (左上角带背景) */
.news-top-time {
  background: rgba(0, 212, 170, 0.1);
  border-radius: 0rpx 24rpx 24rpx 0rpx;
  font-size: 28rpx;
  font-weight: 500;
  color: #00d4aa;
  display: flex;
  align-items: center;
  padding: 5rpx 0rpx;
  width: 100rpx;
}
.news-top-left-line{
    width: 6rpx;
    height: 32rpx;
    background: #06CBB6;
    border-radius: 3rpx;
    margin-right: 16rpx;
  }
/* 快讯标题 */
.news-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1a1a1a;
  line-height: 1.6;
  margin-bottom: 16rpx;
}

/* 快讯描述容器 - 最多显示两行，超出显示省略号 */
.news-desc-wrapper {
  width: 100%;
  font-size: 28rpx;
  color: #606266;
  line-height: 1.8;
  word-break: break-word;
  position: relative;
  max-height: 100.8rpx; /* 28rpx * 1.8 * 2 = 100.8rpx (两行高度) */
  overflow: hidden;
  
  /* 添加渐变遮罩效果（省略号视觉效果） */
  &::after {
    content: '...';
    position: absolute;
    bottom: 0;
    right: 0;
    padding-left: 40rpx;
    background: linear-gradient(to right, transparent, #ffffff 50%);
  }
  
  /* uv-parse 组件样式微调 */
  :deep(.uv-parse-p) {
    margin: 0;
    padding: 0;
    font-size: 28rpx !important;
    color: #606266 !important;
    line-height: 1.8 !important;
    display: inline;
  }
  
  :deep(.uv-parse-img) {
    display: none !important; /* 列表中不显示图片 */
  }
  
  :deep(a) {
    color: #00d4aa !important;
  }
  
  :deep(br) {
    display: none !important; /* 列表中不显示换行 */
  }
  
  :deep(strong), :deep(b) {
    font-weight: 600;
  }
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #c0c4cc;
}
</style>
